package Merlion.CRM.bean;

import Merlion.CRM.entity.SalesLeadEntity;
import Merlion.CRM.entity.LineEntryEntity;
import Merlion.CRM.entity.CustomerEntity;
import Merlion.CRM.entity.BillingAddressEntity;
import Merlion.CRM.entity.CustomerExecutiveEntity;
import Merlion.CRM.entity.ShippingAddressEntity;
import Merlion.CRM.entity.SalesDocumentEntity;
import Merlion.CRM.entity.ContactEntity;
import Merlion.CRM.entity.ClientEntity;

import Merlion.userManagement.bean.CurrentSessionBean;
import Merlion.userManagement.bean.CurrentSessionBeanRemote;
import Merlion.userManagement.entity.RoleEntity;
import Merlion.userManagement.entity.SystemUserEntity;

import Merlion.util.state.AddressState;

import java.util.Collection;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import Merlion.util.state.ClientState;
import Merlion.util.state.ContactState;
import Merlion.util.helper.ClientsAnalysis;
import Merlion.util.state.ContactState;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.persistence.NoResultException;
import javax.persistence.Query;

@Stateless
public class SalesLeadModuleBean implements SalesLeadModuleRemote {

    @PersistenceContext
    EntityManager em;
    @EJB
    private CurrentSessionBeanRemote csb;
    @EJB
    private MessageManagerBeanRemote mmb;

    public SalesLeadModuleBean() {
    }

    public Long addSalesLead(String salutation, String firstName, String lastName, String name, String companyRegId,
            String industry, double annualRevenue, int numOfEmployees,
            String contactNum, String mobileNum, String faxNum, String website,
            double rating, String address, String addressState, String country,
            String city, String postalCode, String emailAddress, String businessType,
            String leadSource, String title, String department, Date dob, String description) {

        //default value, return 0 sales lead is not added successfully 
        String returnIdString = "0";
        Long returnId = Long.parseLong(returnIdString);

        System.out.println("**SalesLeadModuleBean: addSalesLead()");


        System.out.println("Searching for duplicate sales lead data");
        Query q = em.createQuery("Select a from SalesLeadEntity a where a.deleteFlag='N'");

        boolean duplicate = false;
        for (Object o : q.getResultList()) {
            SalesLeadEntity c = (SalesLeadEntity) o;
            if (c.getCompanyRegId().equals(companyRegId)) {
                duplicate = true;
                break;
            }
        }


        if (!duplicate) {
            System.out.println("Duplicate not found");
            SalesLeadEntity salesLead = new SalesLeadEntity();
            String status = "Open";//initialize status, open means this lead has not been contacted

            System.out.println("Get date now");
            Calendar currentDate = Calendar.getInstance();
            SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
            Date dateNow = currentDate.getTime();

            System.out.println("Create sales lead");
            salesLead.create(name, industry, annualRevenue, numOfEmployees, contactNum,
                    addressState, faxNum, website, rating, address, country, city,
                    postalCode, emailAddress, businessType, "SL");
            System.out.println("Persist Sales Lead");
            em.persist(salesLead);
            System.out.println("Setting specific fields");
            salesLead.setSalutation(salutation);
            salesLead.setFirstName(firstName);
            salesLead.setLastName(lastName);
            salesLead.setCompanyRegId(companyRegId);
            salesLead.setStatus(status);
            salesLead.setDateCreated(dateNow);
            salesLead.setLeadSource(leadSource);
            salesLead.setMobileNum(mobileNum);
            salesLead.setTitle(title);
            salesLead.setDepartment(department);
            salesLead.setDob(dob);
            salesLead.setDescription(description);
            em.flush();
            System.out.println("Sales lead persisted");

            returnId = salesLead.getId();
            System.out.println("Sales lead id is : " + returnId);
        }

        System.out.println("Return id is : " + returnId);
        return returnId;
    }

    public void editSalesLead(Long id, String salutation, String firstName, String lastName,
            String name, String industry, double annualRevenue, int numOfEmployees,
            String contactNum, String mobileNum, String faxNum, String website,
            double rating, String address, String addressState, String country,
            String city, String postalCode, String emailAddress, String businessType,
            String status, String leadSource, String title, String department, Date dob, String description) {

        System.out.println("**SalesLeadModuleBean: editSalesLead()");
        System.out.println("Find sales lead");
        SalesLeadEntity salesLead = em.find(SalesLeadEntity.class, id);

        if (salesLead != null && salesLead.getDeleteFlag().equals("N")) {
            System.out.println("Sales lead data found");
            salesLead.setAddress(address);
            salesLead.setCity(city);
            salesLead.setContactNum(contactNum);
            salesLead.setCountry(country);
            salesLead.setEmailAddress(emailAddress);
            salesLead.setName(name);
            salesLead.setPostalCode(postalCode);
            salesLead.setBusinessType(businessType);
            salesLead.setStatus(status);
            salesLead.setSalutation(salutation);
            salesLead.setFirstName(firstName);
            salesLead.setLastName(lastName);
            salesLead.setIndustry(industry);
            salesLead.setAnnualRevenue(annualRevenue);
            salesLead.setNumOfEmployees(numOfEmployees);
            salesLead.setAddressState(addressState);
            salesLead.setFaxNum(faxNum);
            salesLead.setWebsite(website);
            salesLead.setRating(rating);
            salesLead.setMobileNum(mobileNum);
            salesLead.setLeadSource(leadSource);
            salesLead.setTitle(title);
            salesLead.setDepartment(department);
            salesLead.setDob(dob);
            salesLead.setDescription(description);
            em.flush();
            System.out.println("Sales lead data edited.");
        } else {
            System.out.println("No data about sales lead found. Edit sales lead failed.");
        }
    }

    public void deleteSalesLead(Long id) {

        System.out.println("**SalesLeadModuleBean: deleteSalesLead()");
        SalesLeadEntity salesLead = em.find(SalesLeadEntity.class, id);

        if (salesLead != null && salesLead.getDeleteFlag().equals("N")) {
            System.out.println("Sales lead data found");

            //find associated sales document
            System.out.println("Sales lead deleted, sales document also deleted!");
            Query q = em.createQuery("SELECT a from SalesDocumentEntity a where a.client.id =:id").setParameter("id", id);
            for (Object o : q.getResultList()) {
                System.out.println("Sales document found, deleted!");
                SalesDocumentEntity sd = (SalesDocumentEntity) o;
                sd.setDeleteFlag("Y");
            }

            salesLead.setDeleteFlag("Y");
            em.flush();
            System.out.println("Sales lead data deleted");
        } else {
            System.out.println("No sales lead data found. Delete sales lead failed.");
        }
    }

    public Long convertSalesLead(Long id) {
        System.out.println("**SalesLeadModuleBean: convertSalesLead()");
        String returnIdString = "0";
        Long returnId = Long.parseLong(returnIdString);

        System.out.println("Sales lead Id is :" + id);
        
        SalesLeadEntity salesLead = em.find(SalesLeadEntity.class, id);
        CustomerEntity customer = new CustomerEntity();

        if (salesLead != null && salesLead.getDeleteFlag().equals("N")) {
            System.out.println("Sales lead data found");
            System.out.println("Getting data from sales lead");
            String companyRegId = salesLead.getCompanyRegId();
            String name = salesLead.getName();
            String address = salesLead.getAddress();
            String contactNum = salesLead.getContactNum();
            String country = salesLead.getCountry();
            String city = salesLead.getCity();
            String postalCode = salesLead.getPostalCode();
            String emailAddress = salesLead.getEmailAddress();
            String businessType = salesLead.getBusinessType();
            String industry = salesLead.getIndustry();
            double annualRevenue = salesLead.getAnnualRevenue();
            int numOfEmployees = salesLead.getNumOfEmployees();
            String addressState = salesLead.getAddressState();
            String faxNum = salesLead.getFaxNum();
            String website = salesLead.getWebsite();
            double rating = salesLead.getRating();
            String description = salesLead.getDescription();

            System.out.println("Getting fields for creating contact");
            String firstName = salesLead.getFirstName();
            String lastName = salesLead.getLastName();
            String salutation = salesLead.getSalutation();

            String mobileNum = salesLead.getMobileNum();
            String title = salesLead.getTitle();
            String department = salesLead.getDepartment();
            Date dob = salesLead.getDob();

            String leadSource = salesLead.getLeadSource();

            System.out.println("Searching for duplicate customer data");
            Query query = em.createQuery("Select a from CustomerEntity a where a.companyRegId=:companyRegId").setParameter("companyRegId", companyRegId);

            boolean duplicate = false;

            try {
                if (query.getSingleResult() != null) {
                    duplicate = true;
                    CustomerEntity c = (CustomerEntity) query.getSingleResult();
                    returnId = c.getId();
                }
            } catch (NoResultException ex) {
                ex.printStackTrace();
            }

            if (!duplicate) {

                System.out.println("Create customer");
                customer.create(name, industry, annualRevenue, numOfEmployees,
                        contactNum, addressState, faxNum, website, rating,
                        address, country, city, postalCode,
                        emailAddress, businessType, "CU");
                System.out.println("Persist customer");
                em.persist(customer);

                System.out.println("Get date now");
                Calendar currentDate = Calendar.getInstance();
                SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
                Date dateNow = currentDate.getTime();
                customer.setTickerSymbol(" ");
                customer.setOwnership("-None-");
                customer.setSicCode(" ");
                customer.setDateCreated(dateNow);
                customer.setDescription("No description found.");

                List<ContactEntity> contactList = new ArrayList<ContactEntity>();
                customer.setContact(contactList);

                List<BillingAddressEntity> billingList = new ArrayList<BillingAddressEntity>();
                customer.setBillingAddress(billingList);

                List<ShippingAddressEntity> shippingList = new ArrayList<ShippingAddressEntity>();
                customer.setShippingAddress(shippingList);

                Long companyId = customer.getId();
                Long[] arrayAddress = createBillingShippingAddress(companyId, address, addressState, city, postalCode, country,
                        address, addressState, city, postalCode, country);

                Long billingId = arrayAddress[0];
                Long shippingId = arrayAddress[1];

                setPrimaryBillingAddress(billingId, companyId);
                setPrimaryShippingAddress(shippingId, companyId);
                
                System.out.println("Request for credit profile");
                requestForNewCreditProfileAccount(customer.getId(), name);

                ContactEntity contact = new ContactEntity();
                System.out.println("Calling add Contact");
                Long contactId = addContact(salutation, firstName, lastName, companyId, name,
                        leadSource, title, department, contactNum,
                        mobileNum, faxNum, emailAddress, address,
                        addressState, country, city, postalCode,
                        dob, "No description found.");
                if (contactId == 0) {
                    Query q = em.createQuery("Select a from ContactEntity a where a.emailAddress = :emailAddress").setParameter("emailAddress", emailAddress);
                    contact = (ContactEntity) q.getSingleResult();
                } else {
                    contact = em.find(ContactEntity.class, contactId);
                }
                contact.setSalesLead(true);

                em.flush();

                salesLead.setStatus("Converted");
                salesLead.setCustomer(customer);
                em.flush();


                int custSize = 1000;
                String newCustExId = "";
                String newCustExName = "";
                if (getAllCustomerExecutives() != null) {
                    List<SystemUserEntity> systemUserList = getAllCustomerExecutives();
                    if (systemUserList != null || systemUserList.isEmpty()) {
                        for (Object o : systemUserList) {
                            SystemUserEntity systemUser = (SystemUserEntity) o;
                            String custExId = systemUser.getEmail();
                            Query q = em.createQuery("Select a from CustomerEntity a where a.custExId = :custExId").setParameter("custExId", custExId);
                            List<CustomerEntity> customerList = q.getResultList();
                            int size = customerList.size();
                            if (size < custSize) {
                                custSize = size;
                                newCustExId = custExId;
                                newCustExName = systemUser.getName();

                            }
                        }
                        System.out.println("Assigned customer executive is : " + newCustExName);
                        customer.setCustExId(newCustExId);
                        customer.setCustExName(newCustExName);
                        em.flush();
                    }
                }
                
                System.out.println("Sales lead converted");
                returnId = customer.getId();
            } else {
                System.out.println("Duplicate found in the database. Sales Lead is not converted!");
                CustomerEntity c = em.find(CustomerEntity.class, returnId);
                List<ContactEntity> contact = c.getContact();

                System.out.println("Calling add Contact");
                Long contactId = addContact(salutation, firstName, lastName, returnId, name,
                        leadSource, title, department, contactNum,
                        mobileNum, faxNum, emailAddress, address,
                        addressState, country, city, postalCode,
                        dob, "No description found.");

                if (contactId != 0) {
                    ContactEntity con = em.find(ContactEntity.class, contactId);
                    salesLead.setStatus("Converted");
                    em.flush();
                    System.out.println("Contact created!");
                    returnId = Long.parseLong("0");

                } else {
                    System.out.println("Duplicate contact found.");
                    returnId = Long.parseLong("2");
                }

            }

        } else {
            System.out.println("No sales lead found. Convert sales lead failed.");
        }
        System.out.println("Id is " + returnId);
        return returnId;
    }
        
    //for J-Unit testing purposes
     public Long convertSalesLead2(Long id) {
        System.out.println("**SalesLeadModuleBean: convertSalesLead2()");
        String returnIdString = "0";
        Long returnId = Long.parseLong(returnIdString);

        System.out.println("Sales lead Id is :" + id);
        
        SalesLeadEntity salesLead = em.find(SalesLeadEntity.class, id);
        CustomerEntity customer = new CustomerEntity();

        if (salesLead != null && salesLead.getDeleteFlag().equals("N")) {
            System.out.println("Sales lead data found");
            System.out.println("Getting data from sales lead");
            String companyRegId = salesLead.getCompanyRegId();
            String name = salesLead.getName();
            String address = salesLead.getAddress();
            String contactNum = salesLead.getContactNum();
            String country = salesLead.getCountry();
            String city = salesLead.getCity();
            String postalCode = salesLead.getPostalCode();
            String emailAddress = salesLead.getEmailAddress();
            String businessType = salesLead.getBusinessType();
            String industry = salesLead.getIndustry();
            double annualRevenue = salesLead.getAnnualRevenue();
            int numOfEmployees = salesLead.getNumOfEmployees();
            String addressState = salesLead.getAddressState();
            String faxNum = salesLead.getFaxNum();
            String website = salesLead.getWebsite();
            double rating = salesLead.getRating();
            String description = salesLead.getDescription();

            System.out.println("Getting fields for creating contact");
            String firstName = salesLead.getFirstName();
            String lastName = salesLead.getLastName();
            String salutation = salesLead.getSalutation();

            String mobileNum = salesLead.getMobileNum();
            String title = salesLead.getTitle();
            String department = salesLead.getDepartment();
            Date dob = salesLead.getDob();

            String leadSource = salesLead.getLeadSource();

            System.out.println("Searching for duplicate customer data");
            Query query = em.createQuery("Select a from CustomerEntity a where a.companyRegId=:companyRegId").setParameter("companyRegId", companyRegId);

            boolean duplicate = false;

            try {
                if (query.getSingleResult() != null) {
                    duplicate = true;
                    CustomerEntity c = (CustomerEntity) query.getSingleResult();
                    returnId = c.getId();
                }
            } catch (NoResultException ex) {
                ex.printStackTrace();
            }

            if (!duplicate) {

                System.out.println("Create customer");
                customer.create(name, industry, annualRevenue, numOfEmployees,
                        contactNum, addressState, faxNum, website, rating,
                        address, country, city, postalCode,
                        emailAddress, businessType, "CU");
                System.out.println("Persist customer");
                em.persist(customer);

                System.out.println("Get date now");
                Calendar currentDate = Calendar.getInstance();
                SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
                Date dateNow = currentDate.getTime();
                customer.setTickerSymbol(" ");
                customer.setOwnership("-None-");
                customer.setSicCode(" ");
                customer.setDateCreated(dateNow);
                customer.setDescription("No description found.");

                List<ContactEntity> contactList = new ArrayList<ContactEntity>();
                customer.setContact(contactList);

                List<BillingAddressEntity> billingList = new ArrayList<BillingAddressEntity>();
                customer.setBillingAddress(billingList);

                List<ShippingAddressEntity> shippingList = new ArrayList<ShippingAddressEntity>();
                customer.setShippingAddress(shippingList);

                Long companyId = customer.getId();
                Long[] arrayAddress = createBillingShippingAddress(companyId, address, addressState, city, postalCode, country,
                        address, addressState, city, postalCode, country);

                Long billingId = arrayAddress[0];
                Long shippingId = arrayAddress[1];

                setPrimaryBillingAddress(billingId, companyId);
                setPrimaryShippingAddress(shippingId, companyId);

                ContactEntity contact = new ContactEntity();
                System.out.println("Calling add Contact");
                Long contactId = addContact(salutation, firstName, lastName, companyId, name,
                        leadSource, title, department, contactNum,
                        mobileNum, faxNum, emailAddress, address,
                        addressState, country, city, postalCode,
                        dob, "No description found.");
                if (contactId == 0) {
                    Query q = em.createQuery("Select a from ContactEntity a where a.emailAddress = :emailAddress").setParameter("emailAddress", emailAddress);
                    contact = (ContactEntity) q.getSingleResult();
                } else {
                    contact = em.find(ContactEntity.class, contactId);
                }
                contact.setSalesLead(true);

                em.flush();

                salesLead.setStatus("Converted");
                salesLead.setCustomer(customer);
                em.flush();


                //assigned customer executive is hard coded for testing purpose
                 
                customer.setCustExId("anindyapradipta1004@gmail.com");
                customer.setCustExName("Anindya Pradipta");
                em.flush();
       
             
                System.out.println("Sales lead converted");
                returnId = customer.getId();
                
            } else {
                System.out.println("Duplicate found in the database. Sales Lead is not converted!");
                CustomerEntity c = em.find(CustomerEntity.class, returnId);
                List<ContactEntity> contact = c.getContact();

                System.out.println("Calling add Contact");
                Long contactId = addContact(salutation, firstName, lastName, returnId, name,
                        leadSource, title, department, contactNum,
                        mobileNum, faxNum, emailAddress, address,
                        addressState, country, city, postalCode,
                        dob, "No description found.");

                if (contactId != 0) {
                    ContactEntity con = em.find(ContactEntity.class, contactId);
                    salesLead.setStatus("Converted");
                    em.flush();
                    System.out.println("Contact created!");
                    returnId = Long.parseLong("0");

                } else {
                    System.out.println("Duplicate contact found.");
                    returnId = Long.parseLong("2");
                }

            }

        } else {
            System.out.println("No sales lead found. Convert sales lead failed.");
        }
        
        System.out.println("Id is " + returnId);
        return returnId;
    }

    public void updateSalesLeadStatus(Long id, String status) {
        System.out.println("**SalesLeadModuleBean: updateSalesLeadStatus()");
        
        SalesLeadEntity salesLead = em.find(SalesLeadEntity.class, id);

        if (salesLead != null && salesLead.getDeleteFlag().equals("N")) {
            salesLead.setStatus(status);
            em.flush();
            if (status.equals("Converted")) {
                System.out.println("Automatically convert if status is Qualified");
                convertSalesLead(id);
            }
        } else {
            System.out.println("No sales lead data found.");
        }
    }

    public Long addContact(String salutation, String firstName, String lastName, Long companyId, String companyName,
            String leadSource, String title, String department, String contactNum,
            String mobileNum, String faxNum, String emailAddress, String address,
            String addressState, String country, String city, String postalCode,
            Date dob, String description) {

        System.out.println("**SalesLeadModuleBean: addContact()");
        
        String returnIdString = "0";
        Long returnId = Long.parseLong(returnIdString);
        boolean duplicate = false;

        Query q = em.createQuery("Select a from ContactEntity a where a.deleteFlag ='N'");

        for (Object o : q.getResultList()) {
            ContactEntity c = (ContactEntity) o;
            if (c.getEmailAddress().equalsIgnoreCase(emailAddress)) {
                duplicate = true;
                break;
            }
        }

        if (!duplicate) {
            System.out.println("Find customer");
            CustomerEntity customer = em.find(CustomerEntity.class, companyId);
            if (customer != null) {
                companyName = customer.getName();

                System.out.println("Add Contact");
                ContactEntity contact = new ContactEntity();

                contact.create(salutation, firstName, lastName, companyId, companyName, leadSource,
                        title, department, contactNum, mobileNum, faxNum, emailAddress,
                        address, addressState, country, city, postalCode, dob, description);
                System.out.println("Persist contact");
                em.persist(contact);
                contact.setDeleteFlag("N");
                System.out.println("Get date now");
                Calendar currentDate = Calendar.getInstance();
                SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
                Date dateNow = currentDate.getTime();

                contact.setDateCreated(dateNow);

                System.out.println("Associate with customer");

                List<ContactEntity> contactList = customer.getContact();
                contactList.add(contact);
                em.flush();
                returnId = contact.getId();
            } else {
                System.out.println("customer not found");
            }
        }
        return returnId;
    }

    public void editContact(Long id, String salutation, String firstName, String lastName, Long companyId, String companyName,
            String leadSource, String title, String department, String contactNum,
            String mobileNum, String faxNum, String emailAddress, String address,
            String addressState, String country, String city, String postalCode,
            Date dob, String description) {

        System.out.println("**SalesLeadModuleBean: editContact()");
        
        ContactEntity contact = em.find(ContactEntity.class, id);
        if (contact != null && contact.getDeleteFlag() != "Y") {
            contact.setSalutation(salutation);
            contact.setFirstName(firstName);
            contact.setLastName(lastName);
            contact.setLeadSource(leadSource);
            contact.setTitle(title);
            contact.setDepartment(department);
            contact.setContactNum(contactNum);
            contact.setMobileNum(mobileNum);
            contact.setFaxNum(faxNum);
            contact.setEmailAddress(emailAddress);
            contact.setAddress(address);
            contact.setAddressState(addressState);
            contact.setCountry(country);
            contact.setCity(city);
            contact.setPostalCode(postalCode);
            contact.setDob(dob);
            contact.setDescription(description);
            Long companyID = contact.getCompanyId();
            if (companyID != companyId) {
                CustomerEntity customer = em.find(CustomerEntity.class, companyID);
                if (customer != null) {
                    List<ContactEntity> contactList = customer.getContact();
                    contactList.remove(contact);
                    String name = customer.getName();
                    contact.setCompanyId(companyId);
                    contact.setCompanyName(name);
                    CustomerEntity newCustomer = em.find(CustomerEntity.class, companyId);
                    if (newCustomer != null) {
                        String newName = newCustomer.getName();
                        contact.setCompanyName(newName);
                        System.out.println("New company found, set contact to the new company");
                        List<ContactEntity> newContactList = newCustomer.getContact();
                        newContactList.add(contact);
                    }
                }
            }
            em.flush();
            System.out.println("Contact edited");
        }
    }

    public void deleteContact(Long id) {
        System.out.println("**SalesLeadModuleBean: deleteContact()");
        ContactEntity contact = em.find(ContactEntity.class, id);

        if (contact != null) {
            Long companyId = contact.getCompanyId();
            CustomerEntity customer = em.find(CustomerEntity.class, companyId);
            if (customer != null) {
                System.out.println("Remove contact from customer data");
                List<ContactEntity> contactList = customer.getContact();
                contactList.remove(contact);
                em.flush();
            }

        }
        contact.setDeleteFlag("Y");
        em.flush();
    }

    public Long addCustomer(String name, String companyRegId, String industry, double annualRevenue, int numOfEmployees,
            String contactNum, String faxNum, String website,
            double rating, String address, String addressState, String country,
            String city, String postalCode, String emailAddress, String businessType,
            String description, String custExId, String ownership, String tickerSymbol, String sicCode) {
        String returnIdString = "0";
        Long returnId = Long.parseLong(returnIdString);

        System.out.println("**SalesLeadModuleBean: addCustomer()");

        //Search for duplicate data
        System.out.println("Searching for duplicate customer data");
        Query q = em.createQuery("Select a from CustomerEntity a where a.companyRegId=:companyRegId AND a.deleteFlag='N'").setParameter("companyRegId", companyRegId);

        boolean duplicate = false;

        try {
            if (q.getSingleResult() != null) {
                duplicate = true;
            }
        } catch (NoResultException ex) {
            ex.printStackTrace();
        }

        if (!duplicate) {
            System.out.println("No duplicate data found");
            CustomerEntity customer = new CustomerEntity();
            customer.create(name, industry, annualRevenue, numOfEmployees,
                    contactNum, addressState, faxNum, website, rating,
                    address, country, city, postalCode,
                    emailAddress, businessType, "CU");

            System.out.println("Persist customer");
            em.persist(customer);

            //Inititate  billing and shipping list
            List<BillingAddressEntity> billingList = new ArrayList<BillingAddressEntity>();
            customer.setBillingAddress(billingList);

            List<ShippingAddressEntity> shippingList = new ArrayList<ShippingAddressEntity>();
            customer.setShippingAddress(shippingList);
            em.flush();

            Calendar currentDate = Calendar.getInstance();
            SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
            Date dateNow = currentDate.getTime();
            customer.setCompanyRegId(companyRegId);
            customer.setDateCreated(dateNow);
            customer.setTickerSymbol(tickerSymbol);
            customer.setOwnership(ownership);
            customer.setSicCode(sicCode);
            customer.setDescription(description);
            em.flush();
            returnId = customer.getId();
            if (custExId != null) {
                System.out.println(custExId);
                customer.setCustExId(custExId);

                SystemUserEntity su = em.find(SystemUserEntity.class, custExId);
                customer.setCustExName(su.getName());
                em.flush();
            }

            System.out.println("Request for new credit profile account");
            requestForNewCreditProfileAccount(returnId, name);
            
        }
        System.out.println("Return id is : " + returnId);
        return returnId;
    }

    //for J-unit testing
    public Long addCustomer2(String name, String companyRegId, String industry, double annualRevenue, int numOfEmployees,
            String contactNum, String faxNum, String website,
            double rating, String address, String addressState, String country,
            String city, String postalCode, String emailAddress, String businessType,
            String description, String custExId, String ownership, String tickerSymbol, String sicCode) {
        String returnIdString = "0";
        Long returnId = Long.parseLong(returnIdString);

        System.out.println("**SalesLeadModuleBean: addCustomer2()");

        //Search for duplicate data
        System.out.println("Searching for duplicate customer data");
        Query q = em.createQuery("Select a from CustomerEntity a where a.companyRegId=:companyRegId AND a.deleteFlag='N'").setParameter("companyRegId", companyRegId);

        boolean duplicate = false;

        try {
            if (q.getSingleResult() != null) {
                duplicate = true;
            }
        } catch (NoResultException ex) {
        }


        if (!duplicate) {
            System.out.println("No duplicate data found");
            CustomerEntity customer = new CustomerEntity();
            customer.create(name, industry, annualRevenue, numOfEmployees,
                    contactNum, addressState, faxNum, website, rating,
                    address, country, city, postalCode,
                    emailAddress, businessType, "CU");

            System.out.println("Persist customer");
            em.persist(customer);

            //Inititate  billing and shipping list
            List<BillingAddressEntity> billingList = new ArrayList<BillingAddressEntity>();
            customer.setBillingAddress(billingList);

            List<ShippingAddressEntity> shippingList = new ArrayList<ShippingAddressEntity>();
            customer.setShippingAddress(shippingList);
            em.flush();

            Calendar currentDate = Calendar.getInstance();
            SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
            Date dateNow = currentDate.getTime();
            customer.setCompanyRegId(companyRegId);
            customer.setDateCreated(dateNow);
            customer.setTickerSymbol(tickerSymbol);
            customer.setOwnership(ownership);
            customer.setSicCode(sicCode);
            customer.setDescription(description);
            em.flush();
            returnId = customer.getId();
            if (custExId != null) {
                System.out.println(custExId);
                customer.setCustExId(custExId);

                SystemUserEntity su = em.find(SystemUserEntity.class, custExId);
                customer.setCustExName(su.getName());
                em.flush();
            }

            // System.out.println("Request for new credit profile account");
            // requestForNewCreditProfileAccount(returnId, name);
            
        }

        System.out.println("Return id is : " + returnId);
        return returnId;
    }

    public void requestForNewCreditProfileAccount(Long customerId, String customerName) {

        System.out.println("MERLION-EJB ::: Request for New Credit Profile Account");
        System.out.println("Generate email for Finance Executive");

        String title = "Request for New Credit Profile Account";
        String body = "\n" + "\n" + "Automated message from SALES DEPARTMENT to FINANCE DEPARTMENT" + "\n" + "\n"
                + "Request to create new credit profile for the following customer: " + "\n"
                + "=========================" + "\n"
                + "Customer ID     : " + customerId + "\n"
                + "Customer Name   : " + customerName + "\n"
                + "=========================" + "\n" + "\n" + "\n"
                + "Sales Department" + "\n"
                + "Merlion Pte Ltd";

        System.out.println("Sending message");
        mmb.addMessage("Finance Executive", title, body);
        mmb.addMessage("Finance Manager", title, body);
    }

    public BillingAddressEntity addBillingAddress(String billingStreet, String billingCity,
            String billingState, String billingCode, String billingCountry) {

        System.out.println("**SalesLeadModuleBean: addBillingAddress()");
        
        BillingAddressEntity ba = new BillingAddressEntity();
        ba.create(billingStreet, billingCity, billingState, billingCode, billingCountry);
        em.persist(ba);
        Long billingId = ba.getId();

        return ba;

    }

    public void associateBillingAddressWithCustomer(Long customerId, Long addressId) {
        BillingAddressEntity ba = em.find(BillingAddressEntity.class, addressId);
        CustomerEntity customer = em.find(CustomerEntity.class, customerId);

        List<BillingAddressEntity> baList = customer.getBillingAddress();
        baList.add(ba);
        em.flush();
    }

    public void associateShippingAddressWithCustomer(Long customerId, Long addressId) {
        System.out.println("**SalesLeadModuleBean: associateShippingAddressWithCustomer()");
        
        ShippingAddressEntity sa = em.find(ShippingAddressEntity.class, addressId);
        CustomerEntity customer = em.find(CustomerEntity.class, customerId);

        List<ShippingAddressEntity> saList = customer.getShippingAddress();
        saList.add(sa);
        em.flush();
    }

    public ShippingAddressEntity addShippingAddress(String shippingStreet, String shippingCity, String shippingState,
            String shippingCode, String shippingCountry) {
        System.out.println("**SalesLeadModuleBean: addShippingAddress()");
        
        ShippingAddressEntity sa = new ShippingAddressEntity();
        sa.create(shippingStreet, shippingCity, shippingState, shippingCode, shippingCountry);
        em.persist(sa);
        Long shippingId = sa.getId();

        return sa;
    }

    public Long[] createBillingShippingAddress(Long customerId, String billingStreet, String billingCity,
            String billingState, String billingCode, String billingCountry,
            String shippingStreet, String shippingCity, String shippingState,
            String shippingCode, String shippingCountry) {
        Long[] arrayId = new Long[2];

        System.out.println("**SalesLeadModuleBean: createBillingShippingAddress()");
        
        BillingAddressEntity ba = new BillingAddressEntity();
        ba.create(billingStreet, billingCity, billingState, billingCode, billingCountry);
        em.persist(ba);
        Long billingId = ba.getId();
        arrayId[0] = billingId;

        ShippingAddressEntity sa = new ShippingAddressEntity();
        sa.create(shippingStreet, shippingCity, shippingState, shippingCode, shippingCountry);
        em.persist(sa);
        Long shippingId = sa.getId();
        arrayId[1] = shippingId;

        System.out.println("Associate billing and shipping address");
        CustomerEntity customer = em.find(CustomerEntity.class, customerId);
        System.out.println("Customer Data found. Set billing and shipping address");
     
        customer.getBillingAddress().add(ba);

        List<ShippingAddressEntity> shippingList = customer.getShippingAddress();

        shippingList.add(sa);

        em.flush();

        return arrayId;
    }

    public void editBillingAddress(Long id, String bStreet, String bCity, String bState, String bCode,
            String bCountry) {
        System.out.println("**SalesLeadModuleBean: editBillingAddress()");
        
        BillingAddressEntity bAddress = em.find(BillingAddressEntity.class, id);
        if (bAddress != null) {
            bAddress.setBillingStreet(bStreet);
            bAddress.setBillingCity(bCity);
            bAddress.setBillingCode(bCode);
            bAddress.setBillingCountry(bCountry);
            bAddress.setBillingState(bState);
            em.flush();
            System.out.println("Billing Address edited");
        }

    }

    public void editShippingAddress(Long id, String sStreet, String sCity, String sState, String sCode,
            String sCountry) {
        System.out.println("**SalesLeadModuleBean: editShippingAddress()");
        
        ShippingAddressEntity bAddress = em.find(ShippingAddressEntity.class, id);
        if (bAddress != null) {
            bAddress.setShippingStreet(sStreet);
            bAddress.setShippingCity(sCity);
            bAddress.setShippingCode(sCode);
            bAddress.setShippingCountry(sCountry);
            bAddress.setShippingState(sState);
            em.flush();
            System.out.println("Shipping Address edited");
        }
    }

    public void removeShippingAddressfromCustomerData(Long id, Long customerId) {
        System.out.println("**SalesLeadModuleBean: removeShippingAddressfromCustomerData()");
        
        CustomerEntity customer = em.find(CustomerEntity.class, customerId);
        if (customer != null) {
            List<ShippingAddressEntity> shipList = customer.getShippingAddress();
            for (Object o : shipList) {
                ShippingAddressEntity sa = (ShippingAddressEntity) o;
                if (sa.getId() == id) {
                    sa.setDeleteFlag("Y");
                    shipList.remove(sa);
                    break;
                }
            }
        }
        em.flush();
    }

    public void removeBillingAddressfromCustomerData(Long id, Long customerId) {
        System.out.println("**SalesLeadModuleBean: removeBillingAddressfromCustomerData()");

        CustomerEntity customer = em.find(CustomerEntity.class, customerId);
        if (customer != null) {
            List<BillingAddressEntity> billList = customer.getBillingAddress();

            for (Object o : billList) {
                BillingAddressEntity ba = (BillingAddressEntity) o;
                if (ba.getId() == id) {
                    ba.setDeleteFlag("Y");
                    billList.remove(ba);
                    break;
                }
            }
        }
        em.flush();
    }

    public void setPrimaryShippingAddress(Long id, Long customerId) {
        System.out.println("**SalesLeadModuleBean: setPrimaryShippingAddress()");
        
        CustomerEntity customer = em.find(CustomerEntity.class, customerId);
        if (customer != null) {
            List<ShippingAddressEntity> shipList = customer.getShippingAddress();

            for (Object o : shipList) {
                ShippingAddressEntity ba = (ShippingAddressEntity) o;
                ba.setPrimaryAddress(false);
                em.flush();
            }
            for (Object o : shipList) {
                ShippingAddressEntity sa = (ShippingAddressEntity) o;
                if (sa.getId().equals(id)) {
                    System.out.println("shipping address found, set primary");
                    sa.setPrimaryAddress(true);
                    em.flush();
                    break;
                }
            }
        }
    }

    public void setPrimaryBillingAddress(Long id, Long customerId) {
        System.out.println("**SalesLeadModuleBean: setPrimaryBillingAddress()");
        
        CustomerEntity customer = em.find(CustomerEntity.class, customerId);
        if (customer != null) {
            List<BillingAddressEntity> billList = customer.getBillingAddress();
            for (Object o : billList) {
                BillingAddressEntity ba = (BillingAddressEntity) o;
                ba.setPrimaryAddress(false);
                em.flush();
            }
            for (Object o : billList) {
                BillingAddressEntity ba = (BillingAddressEntity) o;
                if (ba.getId().equals(id)) {
                    System.out.println("billing address found, set primary");
                    ba.setPrimaryAddress(true);
                    em.flush();
                    break;
                }
            }
        }
    }

    
    public void editCustomer(Long id, String name, String industry, double annualRevenue, int numOfEmployees,
            String contactNum, String faxNum, String website,
            double rating, String address, String addressState, String country,
            String city, String postalCode, String emailAddress, String businessType,
            String description, String custExId, String ownership, String tickerSymbol, String sicCode) {

        System.out.println("**SalesLeadModuleBean: editCustomer()");
        
        System.out.println("findCustomer");
        CustomerEntity customer = em.find(CustomerEntity.class, id);
        System.out.println("find customer executive");
     
        if (customer != null && customer.getDeleteFlag().equals("N")) {
            System.out.println("Customer data found");
            customer.setAddress(address);
            customer.setCity(city);
            customer.setContactNum(contactNum);
            customer.setCountry(country);
            customer.setEmailAddress(emailAddress);
            customer.setName(name);
            customer.setPostalCode(postalCode);
            customer.setBusinessType(businessType);
            customer.setIndustry(industry);
            customer.setAnnualRevenue(annualRevenue);
            customer.setNumOfEmployees(numOfEmployees);
            customer.setAddressState(addressState);
            customer.setFaxNum(faxNum);
            customer.setWebsite(website);
            customer.setRating(rating);
            customer.setSicCode(sicCode);
            customer.setOwnership(ownership);
            customer.setTickerSymbol(tickerSymbol);
            customer.setDescription(description);
            customer.setCustExId(custExId);
            SystemUserEntity sue = em.find(SystemUserEntity.class, custExId);
            String custExName = sue.getName();
            customer.setCustExName(custExName);
            
            em.flush();
        } else {
            System.out.println("No data about customer found. Edit customer failed.");
        }
    }
    
    
    public void editCustomer2(Long id, String name, String industry, double annualRevenue, int numOfEmployees,
            String contactNum, String faxNum, String website,
            double rating, String address, String addressState, String country,
            String city, String postalCode, String emailAddress, String businessType,
            String description, String custExId, String ownership, String tickerSymbol, String sicCode) {

        System.out.println("**SalesLeadModuleBean: editCustomer()");
        
        System.out.println("findCustomer");
        CustomerEntity customer = em.find(CustomerEntity.class, id);
        System.out.println("find customer executive");
     
        if (customer != null && customer.getDeleteFlag().equals("N")) {
            System.out.println("Customer data found");
            customer.setAddress(address);
            customer.setCity(city);
            customer.setContactNum(contactNum);
            customer.setCountry(country);
            customer.setEmailAddress(emailAddress);
            customer.setName(name);
            customer.setPostalCode(postalCode);
            customer.setBusinessType(businessType);
            customer.setIndustry(industry);
            customer.setAnnualRevenue(annualRevenue);
            customer.setNumOfEmployees(numOfEmployees);
            customer.setAddressState(addressState);
            customer.setFaxNum(faxNum);
            customer.setWebsite(website);
            customer.setRating(rating);
            customer.setSicCode(sicCode);
            customer.setOwnership(ownership);
            customer.setTickerSymbol(tickerSymbol);
            customer.setDescription(description);
           // customer.setCustExId(custExId);
           // SystemUserEntity sue = em.find(SystemUserEntity.class, custExId);
          //  String custExName = sue.getName();
          //  customer.setCustExName(custExName);
            
            em.flush();
        } else {
            System.out.println("No data about customer found. Edit customer failed.");
        }
    }

    public void deleteCustomer(Long id) {
        System.out.println("**SalesLeadModuleBean: deleteCustomer");
        
        CustomerEntity customer = em.find(CustomerEntity.class, id);

        if (customer != null && customer.getDeleteFlag().equals("N")) {
            System.out.println("Customer data found");

            System.out.println("Delete billing and shipping entity");
            List<BillingAddressEntity> billingAddress = customer.getBillingAddress();
            List<ShippingAddressEntity> shippingAddress = customer.getShippingAddress();

            if (billingAddress != null) {
                for (Object o : billingAddress) {
                    BillingAddressEntity ba = (BillingAddressEntity) o;
                    ba.setDeleteFlag("Y");
                }
            }
            if (shippingAddress != null) {
                for (Object o : shippingAddress) {
                    ShippingAddressEntity sa = (ShippingAddressEntity) o;
                    sa.setDeleteFlag("Y");
                }
            }
            

            System.out.println("Delete associated Sales document and line entry");
            Query q = em.createQuery("SELECT a from SalesDocumentEntity a where a.client.id =:id").setParameter("id", id);
            for (Object o : q.getResultList()) {
                SalesDocumentEntity sd = (SalesDocumentEntity) o;
                System.out.println("Sales document found, deleted!");
                sd.setDeleteFlag("Y");
                System.out.println("Delete line entry");
                Collection<LineEntryEntity> lineEntryCollection = sd.getLineEntryList();
                for (Object l : lineEntryCollection) {
                    LineEntryEntity lineEntry = (LineEntryEntity) l;
                    lineEntry.setDeleteFlag("Y");
                }
            }

            System.out.println("Delete contacts");
            List<ContactEntity> contactList = customer.getContact();
            for (Object c : contactList) {
                ContactEntity contact = (ContactEntity) c;
                contact.setDeleteFlag("Y");
            }

            customer.setDeleteFlag("Y");
            em.flush();
            System.out.println("Customer data deleted");
        } else {
            System.out.println("No customer data found. Delete customer failed.");
        }
    }

    
 
    public List<ClientState> viewSalesLeads() {
        System.out.println("**SalesLeadModuleBean: viewSalesLeads");

        Query q = em.createQuery("SELECT c FROM SalesLeadEntity c");
        List stateList = new ArrayList();

        for (Object o : q.getResultList()) {
            SalesLeadEntity c = (SalesLeadEntity) o;
            if (c.getClientType().equals("SL") && c.getDeleteFlag().equals("N") && !c.getStatus().equals("Converted")) {


                ClientState slState = new ClientState(c.getId(), c.getSalutation(), c.getFirstName(), c.getLastName(),
                        c.getName(), c.getIndustry(), c.getAnnualRevenue(), c.getNumOfEmployees(),
                        c.getContactNum(), c.getMobileNum(), c.getFaxNum(), c.getWebsite(), c.getRating(),
                        c.getAddress(), c.getCountry(), c.getCity(), c.getPostalCode(),
                        c.getEmailAddress(), c.getBusinessType(), c.getStatus());
                slState.setContactName(c.getFirstName() + " " + c.getLastName());
                slState.setLeadSource(c.getLeadSource());
                slState.setTitle(c.getTitle());
                slState.setCompanyRegId(c.getCompanyRegId());
                slState.setAddressState(c.getAddressState());
                slState.setDepartment(c.getDepartment());
                slState.setDateCreated(c.getDateCreated());
                slState.setDescription(c.getDescription());

                stateList.add(slState);
            }
        }
        return stateList;
    }

    public List<ClientState> viewCustomers2() {
        System.out.println("**SalesLeadModuleBean: viewCustomers2()");

        Query q = em.createQuery("SELECT c FROM CustomerEntity c");
        List stateList = new ArrayList();
        String custExId = "";
        String custExName = "";
        for (Object o : q.getResultList()) {
            CustomerEntity c = (CustomerEntity) o;
            if (c.getClientType().equals("CU") && c.getDeleteFlag().equals("N")) {
                if (c.getCustExId() == null) {
                    custExId = "";
                    custExName = "Not yet assigned.";
                } else {
                    custExId = c.getCustExId();
                    custExName = c.getCustExName();
                }
                ClientState slState = new ClientState(c.getId(), c.getName(), c.getIndustry(), c.getAnnualRevenue(),
                        c.getNumOfEmployees(), c.getContactNum(), c.getFaxNum(),
                        c.getWebsite(), c.getRating(), c.getAddress(), c.getAddressState(),
                        c.getCountry(), c.getCity(), c.getPostalCode(),
                        c.getEmailAddress(), c.getBusinessType(), custExId, custExName);
                slState.setDateCreated(c.getDateCreated());
                slState.setTickerSymbol(c.getTickerSymbol());
                slState.setSicCode(c.getSicCode());
                slState.setOwnership(c.getOwnership());
                slState.setCustExId(c.getCustExId());
                slState.setCustExName(c.getCustExName());
                slState.setClientType("CU");
                List<AddressState> addressList = new ArrayList<AddressState>();

                BillingAddressEntity ba = new BillingAddressEntity();
                List<BillingAddressEntity> baList = c.getBillingAddress();
                for (Object p : baList) {
                    BillingAddressEntity bAddress = (BillingAddressEntity) p;
                    AddressState billingAddress = new AddressState(bAddress.getId(), bAddress.getBillingStreet(),
                            bAddress.getBillingCity(), bAddress.getBillingState(),
                            bAddress.getBillingCode(), bAddress.getBillingCountry(),
                            bAddress.isPrimaryAddress(), "B");
                    if (bAddress.isPrimaryAddress()) {
                        ba = bAddress;
                        break;
                    }
                    addressList.add(billingAddress);
                }

                slState.setBillingId(ba.getId());
                slState.setBillingCity(ba.getBillingCity());
                slState.setBillingCode(ba.getBillingCode());
                slState.setBillingCountry(ba.getBillingCountry());
                slState.setBillingState(ba.getBillingState());
                slState.setBillingStreet(ba.getBillingStreet());

                ShippingAddressEntity sa = new ShippingAddressEntity();
                List<ShippingAddressEntity> saList = c.getShippingAddress();
                for (Object p : saList) {
                    ShippingAddressEntity sAddress = (ShippingAddressEntity) p;
                    AddressState shippingAddress = new AddressState(sAddress.getId(), sAddress.getShippingStreet(),
                            sAddress.getShippingCity(), sAddress.getShippingState(),
                            sAddress.getShippingCode(), sAddress.getShippingCountry(),
                            sAddress.isPrimaryAddress(), "S");
                    if (sAddress.isPrimaryAddress()) {
                        sa = sAddress;
                        break;
                    }
                    addressList.add(shippingAddress);
                }

                slState.setShippingId(sa.getId());
                slState.setShippingCity(sa.getShippingCity());
                slState.setShippingCode(sa.getShippingCode());
                slState.setShippingCountry(sa.getShippingCountry());
                slState.setShippingState(sa.getShippingState());
                slState.setShippingStreet(sa.getShippingStreet());

                slState.setAddressList(addressList);
                slState.setDescription(c.getDescription());
                stateList.add(slState);
            }
        }

        return stateList;

    }

    public List<ClientState> viewCustomers() {
        System.out.println("**SalesLeadModuleBean: viewCustomers");

        String currentId = csb.getCurrentId();
        SystemUserEntity sue = em.find(SystemUserEntity.class, currentId);

        boolean isManager = false;
        List<SystemUserEntity> userList = new ArrayList<SystemUserEntity>();

        Collection<RoleEntity> roles = sue.getRoles();
        for (Object o : roles) {
            RoleEntity role = (RoleEntity) o;
            if (role.getRoles().equals("Customer Executive Manager")
                    || role.getRoles().equals("President")) {
                isManager = true;
                break;
            }
        }

        Query q = em.createQuery("SELECT c FROM CustomerEntity c");
        List stateList = new ArrayList();
        String custExId = "";
        String custExName = "";
        if (isManager) {
            for (Object o : q.getResultList()) {
                CustomerEntity c = (CustomerEntity) o;
                if (c.getClientType().equals("CU") && c.getDeleteFlag().equals("N")) {
                    if (c.getCustExId() == null) {
                        custExId = "";
                        custExName = "Not yet assigned.";
                    } else {
                        custExId = c.getCustExId();
                        custExName = c.getCustExName();
                    }
                    ClientState slState = new ClientState(c.getId(), c.getName(), c.getIndustry(), c.getAnnualRevenue(),
                            c.getNumOfEmployees(), c.getContactNum(), c.getFaxNum(),
                            c.getWebsite(), c.getRating(), c.getAddress(), c.getAddressState(),
                            c.getCountry(), c.getCity(), c.getPostalCode(),
                            c.getEmailAddress(), c.getBusinessType(), custExId, custExName);
                    slState.setDateCreated(c.getDateCreated());
                    slState.setTickerSymbol(c.getTickerSymbol());
                    slState.setSicCode(c.getSicCode());
                    slState.setOwnership(c.getOwnership());
                    slState.setCustExId(c.getCustExId());
                    slState.setCustExName(c.getCustExName());
                    slState.setClientType("CU");
                    slState.setCompanyRegId(c.getCompanyRegId());
                    List<AddressState> addressList = new ArrayList<AddressState>();

                    BillingAddressEntity ba = new BillingAddressEntity();
                    List<BillingAddressEntity> baList = c.getBillingAddress();
                    for (Object p : baList) {
                        BillingAddressEntity bAddress = (BillingAddressEntity) p;
                        AddressState billingAddress = new AddressState(bAddress.getId(), bAddress.getBillingStreet(),
                                bAddress.getBillingCity(), bAddress.getBillingState(),
                                bAddress.getBillingCode(), bAddress.getBillingCountry(),
                                bAddress.isPrimaryAddress(), "B");
                        if (bAddress.isPrimaryAddress()) {
                            ba = bAddress;
                            break;
                        }
                        addressList.add(billingAddress);
                    }

                    slState.setBillingId(ba.getId());
                    slState.setBillingCity(ba.getBillingCity());
                    slState.setBillingCode(ba.getBillingCode());
                    slState.setBillingCountry(ba.getBillingCountry());
                    slState.setBillingState(ba.getBillingState());
                    slState.setBillingStreet(ba.getBillingStreet());

                    ShippingAddressEntity sa = new ShippingAddressEntity();
                    List<ShippingAddressEntity> saList = c.getShippingAddress();
                    for (Object p : saList) {
                        ShippingAddressEntity sAddress = (ShippingAddressEntity) p;
                        AddressState shippingAddress = new AddressState(sAddress.getId(), sAddress.getShippingStreet(),
                                sAddress.getShippingCity(), sAddress.getShippingState(),
                                sAddress.getShippingCode(), sAddress.getShippingCountry(),
                                sAddress.isPrimaryAddress(), "S");
                        if (sAddress.isPrimaryAddress()) {
                            sa = sAddress;
                            break;
                        }
                        addressList.add(shippingAddress);
                    }

                    slState.setShippingId(sa.getId());
                    slState.setShippingCity(sa.getShippingCity());
                    slState.setShippingCode(sa.getShippingCode());
                    slState.setShippingCountry(sa.getShippingCountry());
                    slState.setShippingState(sa.getShippingState());
                    slState.setShippingStreet(sa.getShippingStreet());

                    slState.setAddressList(addressList);
                    slState.setDescription(c.getDescription());
                    stateList.add(slState);
                }
            }
        } else {
            for (Object o : q.getResultList()) {
                CustomerEntity c = (CustomerEntity) o;
                if (c.getClientType().equals("CU") && c.getDeleteFlag().equals("N")) {
                    if (c.getCustExId() == null) {
                        custExId = "";
                        custExName = "Not yet assigned.";
                    } else {
                        custExId = c.getCustExId();
                        custExName = c.getCustExName();
                    }
                    if (custExId.equals(currentId)) {
                        ClientState slState = new ClientState(c.getId(), c.getName(), c.getIndustry(), c.getAnnualRevenue(),
                                c.getNumOfEmployees(), c.getContactNum(), c.getFaxNum(),
                                c.getWebsite(), c.getRating(), c.getAddress(), c.getAddressState(),
                                c.getCountry(), c.getCity(), c.getPostalCode(),
                                c.getEmailAddress(), c.getBusinessType(), custExId, custExName);
                        slState.setDateCreated(c.getDateCreated());
                        slState.setTickerSymbol(c.getTickerSymbol());
                        slState.setSicCode(c.getSicCode());
                        slState.setOwnership(c.getOwnership());
                        slState.setCustExId(c.getCustExId());
                        slState.setCustExName(c.getCustExName());
                        slState.setClientType("CU");
                        slState.setCompanyRegId(c.getCompanyRegId());

                        List<AddressState> addressList = new ArrayList<AddressState>();

                        BillingAddressEntity ba = new BillingAddressEntity();
                        List<BillingAddressEntity> baList = c.getBillingAddress();
                        for (Object p : baList) {
                            BillingAddressEntity bAddress = (BillingAddressEntity) p;
                            AddressState billingAddress = new AddressState(bAddress.getId(), bAddress.getBillingStreet(),
                                    bAddress.getBillingCity(), bAddress.getBillingState(),
                                    bAddress.getBillingCode(), bAddress.getBillingCountry(),
                                    bAddress.isPrimaryAddress(), "B");
                            if (bAddress.isPrimaryAddress()) {
                                ba = bAddress;
                                break;
                            }
                            addressList.add(billingAddress);
                        }

                        slState.setBillingId(ba.getId());
                        slState.setBillingCity(ba.getBillingCity());
                        slState.setBillingCode(ba.getBillingCode());
                        slState.setBillingCountry(ba.getBillingCountry());
                        slState.setBillingState(ba.getBillingState());
                        slState.setBillingStreet(ba.getBillingStreet());

                        ShippingAddressEntity sa = new ShippingAddressEntity();
                        List<ShippingAddressEntity> saList = c.getShippingAddress();
                        for (Object p : saList) {
                            ShippingAddressEntity sAddress = (ShippingAddressEntity) p;
                            AddressState shippingAddress = new AddressState(sAddress.getId(), sAddress.getShippingStreet(),
                                    sAddress.getShippingCity(), sAddress.getShippingState(),
                                    sAddress.getShippingCode(), sAddress.getShippingCountry(),
                                    sAddress.isPrimaryAddress(), "S");
                            if (sAddress.isPrimaryAddress()) {
                                sa = sAddress;
                                break;
                            }
                            addressList.add(shippingAddress);
                        }

                        slState.setShippingId(sa.getId());
                        slState.setShippingCity(sa.getShippingCity());
                        slState.setShippingCode(sa.getShippingCode());
                        slState.setShippingCountry(sa.getShippingCountry());
                        slState.setShippingState(sa.getShippingState());
                        slState.setShippingStreet(sa.getShippingStreet());

                        slState.setAddressList(addressList);
                        slState.setDescription(c.getDescription());
                        stateList.add(slState);
                    }
                }
            }
        }
        return stateList;
    }

    public List<SystemUserEntity> getAllCustomerExecutives() {
        System.out.println("**SalesLeadModuleBean: getAllCustomerExecutives()");
        
        String currentId = csb.getCurrentId();
        //    String currentRole = csb.getCurrentRole();
        //    System.out.println("Current Role : "+currentRole);
        System.out.println("Current Id : " + currentId);
        SystemUserEntity sue = em.find(SystemUserEntity.class, currentId);

        boolean isManager = false;
        List<SystemUserEntity> userList = new ArrayList<SystemUserEntity>();

        Collection<RoleEntity> roles = sue.getRoles();
        for (Object o : roles) {
            RoleEntity role = (RoleEntity) o;
            if (role.getRoles().equals("Customer Executive Manager") ||
                    role.getRoles().equals("President")) {
                isManager = true;
                break;
            }
        }
        //   List<SystemUserEntity> userList = new ArrayList<SystemUserEntity>();
        if (isManager) {
            System.out.println("Is manager is true");
            Query query = em.createQuery("SELECT c FROM RoleEntity c where c.roles='Customer Executive'");
            List<RoleEntity> role = query.getResultList();

            Query query2 = em.createQuery("SELECT a from SystemUserEntity a JOIN a.roles d where d.roles='Customer Executive'");
            for (Object p : query2.getResultList()) {
                SystemUserEntity user = (SystemUserEntity) p;
                userList.add(user);
            }

        } else {
            userList = new ArrayList<SystemUserEntity>();
            userList.add(sue);
        }

        return userList;
        //   List<CustomerExecutiveEntity> list = new ArrayList<CustomerExecutiveEntity>();
        //   return list;
    }

    public List<ClientState> viewClients() {
        System.out.println("**SalesLeadModuleBean: viewClients()");
        
        Query query = em.createQuery("SELECT c FROM ClientEntity c where c.deleteFlag='N'");
        List<ClientState> stateList = new ArrayList();

        for (Object o : query.getResultList()) {
            ClientEntity c = (ClientEntity) o;

            if (c.getDeleteFlag().equals("N")) {

                ClientState clState = new ClientState(c.getId(), c.getName(), c.getAddress(), c.getContactNum(),
                        c.getCountry(), c.getCity(), c.getPostalCode(), c.getEmailAddress(),
                        c.getBusinessType(), c.getClientType());


                clState.setIndustry(c.getIndustry());
                clState.setCompanyRegId(c.getCompanyRegId());
                clState.setAnnualRevenue(c.getAnnualRevenue());
                clState.setNumOfEmployees(c.getNumOfEmployees());
                clState.setContactNum(c.getContactNum());
                clState.setAddressState(c.getAddressState());
                clState.setFaxNum(c.getFaxNum());
                clState.setWebsite(c.getWebsite());
                clState.setRating(c.getRating());
                clState.setClientType(c.getClientType());
                clState.setDateCreated(c.getDateCreated());
                clState.setDescription(c.getDescription());


                if (c.getClientType().equals("SU")) {
                    SalesLeadEntity sl = (SalesLeadEntity) c;
                    if (!sl.getStatus().equals("Converted")) {
                        stateList.add(clState);
                    }
                } else {
                    stateList.add(clState);
                }
            }
        }

        List<ClientState> customer = viewCustomers();
        for (Object o : customer) {
            ClientState a = (ClientState) o;
            a.setClientType("CU");
        }
        List<ClientState> leads = viewSalesLeads();
        for (Object o : leads) {
            ClientState a = (ClientState) o;
            a.setClientType("SL");
        }

        customer.addAll(leads);

        return customer;
    }
    
    public List<ClientState> viewClients2() {
        System.out.println("**SalesLeadModuleBean: viewClients()");
        
        Query query = em.createQuery("SELECT c FROM ClientEntity c where c.deleteFlag='N'");
        List<ClientState> stateList = new ArrayList();

        for (Object o : query.getResultList()) {
            ClientEntity c = (ClientEntity) o;

            if (c.getDeleteFlag().equals("N")) {

                ClientState clState = new ClientState(c.getId(), c.getName(), c.getAddress(), c.getContactNum(),
                        c.getCountry(), c.getCity(), c.getPostalCode(), c.getEmailAddress(),
                        c.getBusinessType(), c.getClientType());


                clState.setIndustry(c.getIndustry());
                clState.setCompanyRegId(c.getCompanyRegId());
                clState.setAnnualRevenue(c.getAnnualRevenue());
                clState.setNumOfEmployees(c.getNumOfEmployees());
                clState.setContactNum(c.getContactNum());
                clState.setAddressState(c.getAddressState());
                clState.setFaxNum(c.getFaxNum());
                clState.setWebsite(c.getWebsite());
                clState.setRating(c.getRating());
                clState.setClientType(c.getClientType());
                clState.setDateCreated(c.getDateCreated());
                clState.setDescription(c.getDescription());


                if (c.getClientType().equals("SU")) {
                    SalesLeadEntity sl = (SalesLeadEntity) c;
                    if (!sl.getStatus().equals("Converted")) {
                        stateList.add(clState);
                    }
                } else {
                    stateList.add(clState);
                }
            }
        }

        List<ClientState> customer = viewCustomers2();
        for (Object o : customer) {
            ClientState a = (ClientState) o;
            a.setClientType("CU");
        }
        List<ClientState> leads = viewSalesLeads();
        for (Object o : leads) {
            ClientState a = (ClientState) o;
            a.setClientType("SL");
        }

        customer.addAll(leads);

        return customer;
    }

    public boolean checkClientStatus(ClientEntity client) {
        System.out.println("**SalesLeadModuleBean: checkClientStatus()");
        
        List<ClientState> customerList = viewCustomers();
        boolean result = false;

        if (client.getClientType().equals("SL")) {
            System.out.println("Client equals SL");
            result = true;
        } else {
            for (Object o : customerList) {
                ClientState cl = (ClientState) o;
                if (cl.getId().equals(client.getId())) {
                    result = true;
                    break;
                }
            }
        }
        return result;
    }

    public List<ContactState> viewContacts() {
        System.out.println("**SalesLeadModuleBean: viewContacts()");

        String currentId = csb.getCurrentId();
        SystemUserEntity sue = em.find(SystemUserEntity.class, currentId);

        boolean isManager = false;
        List<SystemUserEntity> userList = new ArrayList<SystemUserEntity>();

        Collection<RoleEntity> roles = sue.getRoles();
        for (Object o : roles) {
            RoleEntity role = (RoleEntity) o;
            if (role.getRoles().equals("Customer Executive Manager")) {
                isManager = true;
                break;
            }
        }

        Query query = em.createQuery("SELECT c FROM ContactEntity c where c.deleteFlag='N'");
        List<ContactState> stateList = new ArrayList();

        if (isManager) {
            for (Object o : query.getResultList()) {
                ContactEntity c = (ContactEntity) o;
                if (c.getDeleteFlag().equals("N")) {
                    ContactState ctState = new ContactState(c.getId(), c.getSalutation(), c.getFirstName(), c.getLastName(), c.getCompanyId(),
                            c.getCompanyName(), c.getLeadSource(), c.getTitle(), c.getDepartment(), c.getContactNum(),
                            c.getMobileNum(), c.getFaxNum(), c.getEmailAddress(), c.getAddress(), c.getAddressState(),
                            c.getCountry(), c.getCity(), c.getPostalCode(), c.getDob(), c.getDescription());

                    ctState.setDateCreated(c.getDateCreated());
                    stateList.add(ctState);

                }
            }
        } else {
            List<ClientState> customerList = viewCustomers();
            for (Object o : customerList) {
                ClientState cl = (ClientState) o;
                List<ContactState> contacts = viewContactsForClients(cl.getId());
                stateList.addAll(contacts);
            }
        }
        return stateList;

    }
    
    
     public List<ContactState> viewContacts2() {
        System.out.println("**SalesLeadModuleBean: viewContacts2()");

        boolean isManager=true;
        
        Query query = em.createQuery("SELECT c FROM ContactEntity c where c.deleteFlag='N'");
        List<ContactState> stateList = new ArrayList();

        if (isManager) {
            for (Object o : query.getResultList()) {
                ContactEntity c = (ContactEntity) o;
                if (c.getDeleteFlag().equals("N")) {
                    ContactState ctState = new ContactState(c.getId(), c.getSalutation(), c.getFirstName(), c.getLastName(), c.getCompanyId(),
                            c.getCompanyName(), c.getLeadSource(), c.getTitle(), c.getDepartment(), c.getContactNum(),
                            c.getMobileNum(), c.getFaxNum(), c.getEmailAddress(), c.getAddress(), c.getAddressState(),
                            c.getCountry(), c.getCity(), c.getPostalCode(), c.getDob(), c.getDescription());

                    ctState.setDateCreated(c.getDateCreated());
                    stateList.add(ctState);

                }
            }
        } 
        return stateList;

    }

    public ClientState searchClient(Long id) {
        System.out.println("**SalesLeadModuleBean: searchClient()");
        
        ClientEntity c = em.find(ClientEntity.class, id);

        ClientState clState = new ClientState(c.getId(), c.getName(), c.getAddress(), c.getContactNum(),
                c.getCountry(), c.getCity(), c.getPostalCode(), c.getEmailAddress(),
                c.getBusinessType(), c.getClientType());
        clState.setIndustry(c.getIndustry());
        clState.setAnnualRevenue(c.getAnnualRevenue());
        clState.setCompanyRegId(c.getCompanyRegId());
        clState.setNumOfEmployees(c.getNumOfEmployees());
        clState.setContactNum(c.getContactNum());
        clState.setAddressState(c.getAddressState());
        clState.setFaxNum(c.getFaxNum());
        clState.setWebsite(c.getWebsite());
        clState.setRating(c.getRating());
        clState.setClientType(c.getClientType());
        clState.setDateCreated(c.getDateCreated());
        clState.setDescription(c.getDescription());
        List<AddressState> addressList = new ArrayList<AddressState>();

        if (c.getClientType().equals("CU")) {
            CustomerEntity a = (CustomerEntity) c;
            BillingAddressEntity ba = new BillingAddressEntity();
            List<BillingAddressEntity> baList = a.getBillingAddress();
            for (Object p : baList) {
                BillingAddressEntity bAddress = (BillingAddressEntity) p;
                AddressState billingAddress = new AddressState(bAddress.getId(), bAddress.getBillingStreet(),
                        bAddress.getBillingCity(), bAddress.getBillingState(),
                        bAddress.getBillingCode(), bAddress.getBillingCountry(),
                        bAddress.isPrimaryAddress(), "B");
                if (bAddress.isPrimaryAddress()) {
                    ba = bAddress;
                }
                addressList.add(billingAddress);
            }

            clState.setBillingId(ba.getId());
            clState.setBillingCity(ba.getBillingCity());
            clState.setBillingCode(ba.getBillingCode());
            clState.setBillingCountry(ba.getBillingCountry());
            clState.setBillingState(ba.getBillingState());
            clState.setBillingStreet(ba.getBillingStreet());

            ShippingAddressEntity sa = new ShippingAddressEntity();
            List<ShippingAddressEntity> saList = a.getShippingAddress();
            for (Object p : saList) {
                ShippingAddressEntity sAddress = (ShippingAddressEntity) p;
                AddressState shippingAddress = new AddressState(sAddress.getId(), sAddress.getShippingStreet(),
                        sAddress.getShippingCity(), sAddress.getShippingState(),
                        sAddress.getShippingCode(), sAddress.getShippingCountry(),
                        sAddress.isPrimaryAddress(), "S");
                if (sAddress.isPrimaryAddress()) {
                    sa = sAddress;
                }
                addressList.add(shippingAddress);
            }

            clState.setShippingId(sa.getId());
            clState.setShippingCity(sa.getShippingCity());
            clState.setShippingCode(sa.getShippingCode());
            clState.setShippingCountry(sa.getShippingCountry());
            clState.setShippingState(sa.getShippingState());
            clState.setShippingStreet(sa.getShippingStreet());

            clState.setAddressList(addressList);
        }

        return clState;
    }

    public List<ClientState> viewConvertedLeads() {
        System.out.println("**SalesLeadModuleBean: viewConvertedLeads()");

        Query q = em.createQuery("SELECT c FROM SalesLeadEntity c");
        List stateList = new ArrayList();

        for (Object o : q.getResultList()) {
            SalesLeadEntity c = (SalesLeadEntity) o;
            if (c.getClientType().equals("SL") && c.getStatus().equals("Converted") && c.getDeleteFlag().equals("N")) {

                //    System.out.println(c.getSalutation());
                ClientState slState = new ClientState(c.getId(), c.getSalutation(), c.getFirstName(), c.getLastName(),
                        c.getName(), c.getIndustry(), c.getAnnualRevenue(), c.getNumOfEmployees(),
                        c.getContactNum(), c.getMobileNum(), c.getFaxNum(), c.getWebsite(), c.getRating(),
                        c.getAddress(), c.getCountry(), c.getCity(), c.getPostalCode(),
                        c.getEmailAddress(), c.getBusinessType(), c.getStatus());
                slState.setContactName(c.getFirstName() + " " + c.getLastName());
                slState.setLeadSource(c.getLeadSource());
                slState.setCompanyRegId(c.getCompanyRegId());
                slState.setTitle(c.getTitle());
                slState.setAddressState(c.getAddressState());
                slState.setDepartment(c.getDepartment());
                slState.setDateCreated(c.getDateCreated());
                slState.setDescription(c.getDescription());

                stateList.add(slState);
            }
        }
        return stateList;
    }

    public ContactState searchContact(Long id) {
        System.out.println("**SalesLeadModuleBean: searchContacts()");
        
        // Query query = em.createQuery("SELECT c FROM ContactEntity c where c.deleteFlag='N'");
        //List<ContactState> stateList = new ArrayList();
        ContactEntity c = em.find(ContactEntity.class, id);

        ContactState ctState = new ContactState(c.getId(), c.getSalutation(), c.getFirstName(), c.getLastName(), c.getCompanyId(),
                c.getCompanyName(), c.getLeadSource(), c.getTitle(), c.getDepartment(), c.getContactNum(),
                c.getMobileNum(), c.getFaxNum(), c.getEmailAddress(), c.getAddress(), c.getAddressState(),
                c.getCountry(), c.getCity(), c.getPostalCode(), c.getDob(), c.getDescription());

        ctState.setDateCreated(c.getDateCreated());

        return ctState;
    }

    public AddressState searchBillingAddress(Long id) {
        System.out.println("**SalesLeadModuleBean: searchBillingAddress()");

        BillingAddressEntity ba = em.find(BillingAddressEntity.class, id);

        AddressState adState = new AddressState(id, ba.getBillingStreet(), ba.getBillingCity(), ba.getBillingState(), ba.getBillingCode(),
                ba.getBillingCountry(), ba.isPrimaryAddress(), "B");

        return adState;
    }

    public AddressState searchShippingAddress(Long id) {
        System.out.println("**SalesLeadModuleBean: searchShippingAddress()");

        ShippingAddressEntity ba = em.find(ShippingAddressEntity.class, id);

        AddressState adState = new AddressState(id, ba.getShippingStreet(), ba.getShippingCity(), ba.getShippingState(), ba.getShippingCode(),
                ba.getShippingCountry(), ba.isPrimaryAddress(), "S");

        return adState;
    }

    public int countLeads(int month) {
        System.out.println("**SalesLeadModuleBean: countLeads()");

        Query q = em.createQuery("SELECT a from SalesLeadEntity a");
        int count = 0;

        for (Object o : q.getResultList()) {
            SalesLeadEntity sl = (SalesLeadEntity) o;

            Date date = sl.getDateCreated();
            SimpleDateFormat sdf = new SimpleDateFormat("MM");
            String monthInString = sdf.format(date);
            int monthInt = Integer.parseInt(monthInString);

            if (monthInt == month) {
                count++;
                System.out.println("count : " + count);
            }
        }
        return count;
    }

    public int countClients(int month) {
        System.out.println("**SalesLeadModuleBean: countClients()");

        Query q = em.createQuery("SELECT a from ClientEntity a");
        int count = 0;

        for (Object o : q.getResultList()) {
            ClientEntity sl = (ClientEntity) o;

            Date date = sl.getDateCreated();
            SimpleDateFormat sdf = new SimpleDateFormat("MM");
            String monthInString = sdf.format(date);
            int monthInt = Integer.parseInt(monthInString);

            if (monthInt == month) {
                count++;
                System.out.println("count : " + count);
            }
        }
        return count;
    }

    public int countCustomers(int month) {
        System.out.println("**SalesLeadModuleBean: countCustomers()");

        Query q = em.createQuery("SELECT a from CustomerEntity a");
        int count = 0;

        for (Object o : q.getResultList()) {
            CustomerEntity sl = (CustomerEntity) o;

            Date date = sl.getDateCreated();
            SimpleDateFormat sdf = new SimpleDateFormat("MM");
            String monthInString = sdf.format(date);
            int monthInt = Integer.parseInt(monthInString);

            if (monthInt == month) {
                count++;
                System.out.println("count : " + count);
            }
        }
        return count;
    }

    public List<ClientsAnalysis> getLeadList() {
        System.out.println("**SalesLeadModuleBean: getLeadList()");

        List<ClientsAnalysis> leadList = new ArrayList<ClientsAnalysis>();
        int count = 0;

        for (int i = 1; i <= 12; i++) {
            count = countLeads(i);
            ClientsAnalysis lead = new ClientsAnalysis(i, count);
            System.out.println("I = " + i + " Count : " + count);
            leadList.add(lead);
        }
        return leadList;
    }

    public List<ClientsAnalysis> getClientList() {
        System.out.println("**SalesLeadModuleBean: getClientList()");

        List<ClientsAnalysis> leadList = new ArrayList<ClientsAnalysis>();
        int count = 0;

        for (int i = 1; i <= 12; i++) {
            count = countClients(i);
            ClientsAnalysis lead = new ClientsAnalysis(i, count);
            System.out.println("I = " + i + " Count : " + count);
            leadList.add(lead);
        }
        return leadList;
    }

    public List<ClientsAnalysis> getCustomerList() {
        System.out.println("**SalesLeadModuleBean: getCustomerList()");

        List<ClientsAnalysis> leadList = new ArrayList<ClientsAnalysis>();
        int count = 0;

        for (int i = 1; i <= 12; i++) {
            count = countCustomers(i);
            ClientsAnalysis lead = new ClientsAnalysis(i, count);
            System.out.println("I = " + i + " Count : " + count);
            leadList.add(lead);
        }
        return leadList;
    }

    public List<ContactState> viewContactsForClients(Long id) {
        System.out.println("**SalesLeadModuleBean: viewContactsForClients()");
        
        CustomerEntity customer = em.find(CustomerEntity.class, id);
        List<ContactState> cList = new ArrayList<ContactState>();
        if (customer != null) {
            System.out.println("customer not null, get contact list");
            List<ContactEntity> contactList = customer.getContact();
            for (Object o : contactList) {
                ContactEntity c = (ContactEntity) o;
                if (c.getDeleteFlag().equals("N")) {
                    ContactState ctState = new ContactState(c.getId(), c.getSalutation(), c.getFirstName(), c.getLastName(), c.getCompanyId(),
                            c.getCompanyName(), c.getLeadSource(), c.getTitle(), c.getDepartment(), c.getContactNum(),
                            c.getMobileNum(), c.getFaxNum(), c.getEmailAddress(), c.getAddress(), c.getAddressState(),
                            c.getCountry(), c.getCity(), c.getPostalCode(), c.getDob(), c.getDescription());

                    ctState.setDateCreated(c.getDateCreated());
                    cList.add(ctState);
                }
            }

        }
        return cList;
    }


}
